import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

import { getParkCashflowRank } from '@/api/rank'

// 状态类型
// 定义 CounterState 类型

const initialState = {
  value: 0,
  videosList: [],
  waitVideosList: [],
  enterLoading: true,
  totalAmount: 0,
  appName: '',
  flvPlayerControl: [],
}

/**
 * Counter 模块的 Redux slice
 */
const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
    setTotalAmount: (state, action) => {
      state.totalAmount = action.payload
    },
    setAppName: (state, action) => {
      state.appName = action.payload
    },
    setFlvPlayerControl: (state, action) => {
      console.log(action.payload)
      state.flvPlayerControl = state.flvPlayerControl.concat(action.payload)
      console.log('store', state.flvPlayerControl)
    },
    removeFlvPlayerControl: (state) => {
      state.flvPlayerControl = []
    },
    // getVideosList: async (state, action) => {
    //   try {
    //     const res = await getParkCashflowRank(action.payload)
    //     console.log(res)
    //     // state.videosList = res.data.list
    //     return res.data.list
    //   } catch (error) {
    //     console.log(error)
    //   }
    //   // getParkCashflowRank(action.payload).then((res) => {
    //   //   console.log(res)
    //   //   state.videosList = res.data.list
    //   // })
    // },
    addWaitVideos: (state, action) => {
      console.log(action.payload)
    },
  },
  //用于处理异步不同状态
  extraReducers(builder) {
    builder
      .addCase(getVideosList.pending, (state) => {
        //Promise.pending状态时执行
        console.log('🚀 ~ 进行中！')
      })
      .addCase(getVideosList.fulfilled, (state, { payload }) => {
        //Promise.fulfiled状态时执行，真正修改state的逻辑放此处
        console.log('🚀 ~ fulfilled', payload)
        state.videosList = payload.data.list
        state.enterLoading = false
      })
      .addCase(getVideosList.rejected, (state, err) => {
        //Promise.rejected状态时执行
        console.log('🚀 ~ rejected', err)
      })
  },
})

//导出异步方法，第一个参数是命名空间，也是在redux-devtool显示的name，第二个参数是dispatch传入的参数
export const getVideosList = createAsyncThunk(
  'counter/getParkCashflowRank',
  async (params) => {
    return await getParkCashflowRank(params)
  }
)

// 导出 actions 和 reducer
export const {
  increment,
  decrement,
  incrementByAmount,
  setTotalAmount,
  setAppName,
  setFlvPlayerControl,
  removeFlvPlayerControl,
} = counterSlice.actions
export default counterSlice.reducer
